select Sum(A.attrspermotype * B.instancespermotype) as totStatsAttrs, Sum(A.kpiattrspermotype * B.instancespermotype) as totKPIAttrs from (select am.motypeid as motypeid, count(*) as attrspermotype, sum(case am.bitfield & 1 when 0 then 0 else 1 end) as kpiattrspermotype from attribute_meta am where am.attrtype=4 and (uniquename != 'PN_DUMMY_STATS') and (mask & 512) > 0 group by am.motypeid) A join (select ic.motypeid as motypeid, count(*) as instancespermotype from item_cfg ic group by ic.motypeid) B on A.motypeid = B.motypeid